/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package financialapplication;

import java.awt.BorderLayout;
import java.sql.Connection;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;

import org.jfree.data.xy.DefaultHighLowDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;
import java.sql.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.sql.*;
import java.util.Date;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.XYPlot;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.net.*;
import java.io.*;
import javax.swing.SwingUtilities;

public class CandleStickChart extends ApplicationFrame {

    JComboBox jc = new JComboBox();
    int count = 0;
    String s;
    String fll = "F:/Development/Workspace/Netbeans Workspace/Financial Application/VIJAYABANK.csv";
    public String[] des = {"JSWISPAT","TCS","HEXAWARE","SHASUNPHAR","CAIRN","TATAMOTORS","L&TFH","RELIANCE","VIJAYABANK","NMDC","LT","ACC","ALBK","BHARTIARTL","PNB","RANBAXY","BIOCON","JPASSOCIAT","","CANBK","MARUTI","SAIL","HEROHONDA","HDFC","HINDUNILVR","ITC","ONGC","SBIN","SUZLON","TATASTEEL"};
    DefaultHighLowDataset dataset;
    JFreeChart chart;
    ChartPanel chartPanel;
    JPanel jp = new JPanel();

    public CandleStickChart(String titel) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException, ParseException {
        super(titel);


        while (count < des.length) {
            jc.addItem(des[count++]);
        }


        setContentPane(jp);
        jp.setLayout(new BorderLayout());

        jp.add(jc, BorderLayout.NORTH);
        jc.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                try {
                    FileWriter fstream = new FileWriter(((JComboBox) e.getSource()).getSelectedItem().toString() + ".csv");
                    URL u = new URL("http://www.nseindia.com/content/equities/historical/" +((JComboBox) e.getSource()).getSelectedItem().toString() + ".csv");
                    fll = "F:/Development/Workspace/Netbeans Workspace/Financial Application/" +((JComboBox) e.getSource()).getSelectedItem().toString() + ".csv";


                    SwingUtilities.invokeLater(new Runnable() {

                        public void run() {
                            try {
                                jp.remove(chartPanel);
                                dataset = createDataset(fll);
                                chart = createChart(dataset);
                                chartPanel = new ChartPanel(chart);
                                chartPanel.setPreferredSize(new java.awt.Dimension(1366,650));
                                jp.add(chartPanel, BorderLayout.SOUTH);
                                pack();
                                setVisible(true);
                            } catch (ClassNotFoundException ex) {
                                Logger.getLogger(CandleStickChart.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (InstantiationException ex) {
                                Logger.getLogger(CandleStickChart.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (IllegalAccessException ex) {
                                Logger.getLogger(CandleStickChart.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (SQLException ex) {
                                Logger.getLogger(CandleStickChart.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (ParseException ex) {
                                Logger.getLogger(CandleStickChart.class.getName()).log(Level.SEVERE, null, ex);
                            }

                        }
                    });





                    InputStream is = u.openStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                    BufferedWriter out = new BufferedWriter(fstream);
                    br.readLine();
                    while ((s = br.readLine()) != null) {
                        out.write(s + "\n");
                    }
                    out.close();

                } catch (MalformedURLException me) {
                } catch (IOException ie) {
                }


            }
        });


        dataset = createDataset(fll);
        chart = createChart(dataset);
        chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new java.awt.Dimension(1336, 650));
        jp.add(chartPanel, BorderLayout.SOUTH);




        // setContentPane(chartPanel);
    }

    private DefaultHighLowDataset createDataset(String m) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException, ParseException {

        int serice = 15;
        String file = m;

        Date date[] = new Date[30];
        DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
        double[] high = new double[30];
        double[] low = new double[30];
        double[] open = new double[30];
        double[] close = new double[30];
        double[] volume = new double[30];
        String dbtime;
        Connection conn = null;
        String userName = "root";
        String password = "root";
        Statement dr;
        int k = 0;
        ResultSet res;
        String url = "jdbc:mysql://localhost:3306/finance";
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        conn = DriverManager.getConnection(url, userName, password);
        dr = conn.createStatement();
        dr.executeUpdate("truncate table vijaya");
        String query1 = "LOAD DATA INFILE '" + file
                + "' INTO TABLE vijaya FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\n';";

        dr.executeUpdate(query1);



        String query = "select * from vijaya";
        ResultSet rs = dr.executeQuery(query);

        while (rs.next()) {
            date[k] = formatter.parse(rs.getString(3));
            high[k] = rs.getDouble(6);
            low[k] = rs.getDouble(7);
            open[k] = rs.getDouble(5);
            close[k] = rs.getDouble(9);
            volume[k] = rs.getDouble(11);
            ++k;
        }


        conn.close();

        Calendar calendar = Calendar.getInstance();
        calendar.set(2008, 20, 1);



        DefaultHighLowDataset data = new DefaultHighLowDataset(
                "", date, high, low, open, close, volume);
        return data;
    }

    private JFreeChart createChart(final DefaultHighLowDataset dataset) {
        final JFreeChart chart = ChartFactory.createCandlestickChart(
                "Candlestick Demo", "Time", "Price", dataset, false);
        return chart;
    }

    public static void main(String args[]) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException, ParseException {
        CandleStickChart chart = new CandleStickChart("Candle Stick Chart");
        chart.pack();
        RefineryUtilities.centerFrameOnScreen(chart);
        chart.setVisible(true);

    }
}
